﻿using PLCS.Domain.Orders;
using PLCS.EntityFrameworkCore.EntityFrameworkCore;

namespace PLCS.EntityFrameworkCore.Orders;

internal class OrderRepository : EfCoreRepository<PLCSDbContext, Order, Guid>, IOrderRepository
{
    public OrderRepository(IDbContextProvider<PLCSDbContext> dbContextProvider) : base(dbContextProvider)
    {
    }

    public async Task ChangeOrderStatusAsync(string orderNo, OrderStatus status)
    {
        var dbContext = await GetDbContextAsync();
        var order = await dbContext.Orders.Where(x => x.OrderNo == orderNo).FirstOrDefaultAsync();
        Check.NotNull(order, orderNo, $"不存在订单:{orderNo}");
        order.ChangeStatus(status);
        await dbContext.SaveChangesAsync();
    }

    public async Task<Order?> FindOrderByNoAsync(string orderNo)
    {
        var dbContext = await GetDbContextAsync();
        var order = await FindAsync(x => x.OrderNo == orderNo);
        if (order != null)
            order.OrderRunningConditions = await dbContext.OrderRunningConditions.Where(x => x.OrderNo == order.OrderNo).OrderBy(x => x.WhichStep).ToListAsync();
        return order;
    }

    public async Task<IEnumerable<Order>> GetOrderListAsync(Expression<Func<Order, bool>> predicate)
    {
        var dbContext = await GetDbContextAsync();
        var orders = dbContext.Orders.Where(predicate);
        foreach (var item in orders)
        {
            item.OrderRunningConditions = await dbContext.OrderRunningConditions.Where(x => x.OrderNo == item.OrderNo).OrderBy(x => x.WhichStep).ToListAsync();
        }
        return orders;
    }

    public async Task<IEnumerable<Order>> GetOrderListAsync()
    {
        var dbContext = await GetDbContextAsync();
        var orders = dbContext.Orders;
        foreach (var item in orders)
        {
            item.OrderRunningConditions = await dbContext.OrderRunningConditions.Where(x => x.OrderNo == item.OrderNo).OrderBy(x => x.WhichStep).ToListAsync();
        }
        return orders;
    }
}